[autocomplete] Fix scroll resets to top on option selection when popup is reopened on clicking the input #47248
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes #47203
Fix: prevent listbox scroll from resetting to top after selection when reopened via input click
Issue explanation
When
disableCloseOnSelectis enabled in<Autocomplete />, the listbox's scroll position jumps back to the top after selecting an option and reopening the popup by clicking on the input.This does not happen when the popup is closed by clicking outside and then reopened.
Steps to Reproduce
<Autocomplete multiple disableCloseOnSelect />with enough options to make the listbox scrollable.Expected: The listbox should keep its current scroll position.
Actual: The listbox scrolls back to the top.
Why it Happened
The effect below was always re-running
syncHighlightedIndex()whenever the popup was open:When closing via input click, there is an intermediate render with
popupOpen = false, causingfilteredOptions = []to be stored inpreviousProps.filteredOptions.On reopening,
filteredOptionsbecomes non-empty again, sofilteredOptionsChangedistrue.The effect runs during option selection, and
syncHighlightedIndex()resets the highlighted index to-1, which setslistboxNode.scrollTop = 0, causing the scroll jump.When closing by clicking outside, the input blurs and the listbox ref unmounts; reopening triggers
handleListboxRef()to sync the highlighted index after mount instead. In this path,previousProps.filteredOptionsstays filled, sofilteredOptionsChangedisfalse, and the scroll position is preserved.Fix
Run the sync effect on popup open only when
disableCloseOnSelectis not set:This prevents unnecessary synchronization while the popup remains open for multi-select use cases.
Test Added
Added a regression test verifying that:
Before: https://stackblitz.com/edit/h6i4uehm-igrkcoz4?file=src%2FDemo.tsx
After: https://stackblitz.com/edit/jbaa3hry?file=src%2FApp.tsx